package cn.qidd.keep.common;

import cn.qidd.keep.domain.config.ApplicationRunConfig;
import cn.qidd.keep.domain.config.MessageSourceConfig;
import cn.qidd.keep.domain.config.RedisConfig;
import cn.qidd.keep.domain.config.Swagger2Config;
import cn.qidd.keep.domain.web.ControllerExceptionHandleAdvice;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.*;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.web.client.RestTemplate;

import java.net.UnknownHostException;

@Import({Swagger2Config.class, RedisConfig.class, MessageSourceConfig.class})
//@EnableElasticsearchRepositories(basePackages = "cn.qidd.keep.common.repository.elastic")
@EnableMongoRepositories(basePackages = "cn.qidd.keep.common.repository")
//@EnableJpaRepositories(basePackages = "cn.qidd.keep.common.repository.jpa")
@EntityScan("cn.qidd.keep.domain.entity")
@ComponentScan(basePackages = "cn.qidd.keep.common", basePackageClasses = {ControllerExceptionHandleAdvice.class})
@EnableDiscoveryClient
@SpringBootApplication
public class CommonApplication {

    private static final Logger logger = LoggerFactory.getLogger(CommonApplication.class);

    public static void main(String[] args) throws UnknownHostException {
        SpringApplication application = new SpringApplication(CommonApplication.class);
        ApplicationRunConfig.runConfig(application, args, logger);
    }

    @Profile("dev")
    @Configuration
    public class SecurityPermitAllConfig extends WebSecurityConfigurerAdapter {

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests().anyRequest().permitAll()
                    .and().csrf().disable();
        }
    }

    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}
